package com.tsing.bms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsing.bms.entity.Unit;
import com.tsing.bms.mapper.UnitMapper;
import com.tsing.bms.service.IUnitService;
import com.tsing.bms.vo.req.IdReqVo;
import com.tsing.bms.vo.req.IdsReqVo;
import com.tsing.bms.vo.req.UnitAddReqVo;
import com.tsing.bms.vo.req.UnitUpdateReqVo;
import com.tsing.bms.vo.resp.UnitRespVo;
import com.tsing.common.exceptions.BusinessException;
import com.tsing.common.exceptions.ServerException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author TheTsing
 * @since 2021-03-29
 */
@Service
public class UnitServiceImpl extends ServiceImpl<UnitMapper, Unit> implements IUnitService {

    @Override
    public void addUnit(UnitAddReqVo reqVo) {
//        if (0 != baseMapper.selectCount(new QueryWrapper<Unit>().eq("name", reqVo.getName()))) {
//            throw new BusinessException(ServerException.Proxy.NAME_HAVE_RELEVANCE);
//        }
        Unit unit = new Unit();
        BeanUtils.copyProperties(reqVo, unit);
        baseMapper.insert(unit);
    }

    @Override
    public void deleteUnit(IdsReqVo reqVo) {
        if (!StringUtils.isBlank(baseMapper.haveRelevance(reqVo.getIds()))) {
            throw new BusinessException(ServerException.Proxy.UNIT_HAVE_RELEVANCE);
        }
        baseMapper.deleteBatchIds(reqVo.getIds());
    }

    @Override
    public UnitRespVo getUnitById(IdReqVo reqVo) {
        UnitRespVo unitRespVo = new UnitRespVo();
        BeanUtils.copyProperties(baseMapper.selectById(reqVo.getId()), unitRespVo);
        return unitRespVo;
    }

    @Override
    public void updateUnit(UnitUpdateReqVo reqVo) {
//        if (0 != baseMapper.selectCount(new QueryWrapper<Unit>().eq("name", reqVo.getName())
//                .ne("id", reqVo.getId()))) {
//            throw new BusinessException(ServerException.Proxy.NAME_HAVE_RELEVANCE);
//        }
        Unit unit = new Unit();
        BeanUtils.copyProperties(reqVo, unit);
        baseMapper.updateById(unit);
    }

    @Override
    public List<UnitRespVo> unitList() {
        List<UnitRespVo> unitRespVos = baseMapper.unitList();
        unitRespVos.forEach(e -> {
            e.setHouseCount(baseMapper.findHouseCount(e.getId()));
            e.setCqyzCount(baseMapper.findCqyzCount(e.getId()));
            e.setRzyzCount(baseMapper.findRzyzCount(e.getId()));
            e.setRzzhCount(baseMapper.findRzzhCount(e.getId()));
        });
        return unitRespVos;
    }
}
